## 1. 读取原图并转换为灰度图像
import cv2
import numpy as np

# 读取原图
image_0 = cv2.imread("hanzi1.jpg")
# 将原图转换为灰度图像
image_1 = cv2.cvtColor(image_0, cv2.COLOR_BGR2GRAY)
# 保存灰度图像
cv2.imwrite('image_1.jpg', image_1)

## 2. 阈值处理和二值化
# 将灰度图image_1阈值200处理转换为二值图
_, image_2 = cv2.threshold(image_1, 90, 255, cv2.THRESH_BINARY)
# 反转
image_2 = np.bitwise_not(image_2)
# 保存二值图像
cv2.imwrite('image_2.jpg', image_2)

## 3. 腐蚀操作去除噪点
# 进行腐蚀操作去除噪点
image_2 = cv2.imread('image_2.jpg', cv2.IMREAD_GRAYSCALE)
# 创建的5*5的十字形结构元素
kernel = np.array([[0,0,1,0,0],
                   [0,1,1,1,0],
                   [1,1,1,1,1],
                   [0,1,1,1,0],
                   [0,0,1,0,0]], dtype=np.uint8)
# 进行腐蚀操作，迭代3次增强腐蚀效果
image_3 = cv2.erode(image_2, kernel, iterations=2)
# 保存腐蚀后的图像
cv2.imwrite('image_3.jpg', image_3)

## 4. 膨胀操作和中值滤波
# 进行膨胀操作突出图像特征
# 用3*3的十字形结构元素进行膨胀操作
kernel = np.array([[0,1,0],
                   [1,1,1],
                   [0,1,0]], dtype=np.uint8)
image_4 = cv2.dilate(image_3, kernel, iterations=2)
# 对image_4进行中值滤波去除小白点
image_4 = cv2.medianBlur(image_4, 9)
# 保存膨胀后的图像
cv2.imwrite('image_4.jpg', image_4)

## # 进行膨胀操作突出图像特征
# 用3*3的十字形结构元素进行膨胀操作
kernel = np.array([[0,1,0],
                   [1,1,1],
                   [0,1,0]], dtype=np.uint8)
image_4 = cv2.dilate(image_3, kernel, iterations=2)
# 对image_4进行中值滤波去除小白点
image_4 = cv2.medianBlur(image_4, 9)
# 保存膨胀后的图像
cv2.imwrite('image_4.jpg', image_4)

## 5. 闭运算填充闭合区域
# 运用闭运算填充闭合区域
kernel = np.ones((100,100), np.uint8)
image_5 = cv2.morphologyEx(image_4, cv2.MORPH_CLOSE, kernel)
# 保存闭运算后的图像
cv2.imwrite('image_5.jpg', image_5)

## 6. Canny边缘检测提取边缘
# Canney边缘检测提取边缘
image_5 = cv2.imread('image_5.jpg', cv2.IMREAD_GRAYSCALE)
# 应用Canny边缘检测
image_6 = cv2.Canny(image_5, 200,200)
# 保存边缘检测结果
cv2.imwrite('image_6.jpg',image_6)

## 7. 识别结果并绘制轮廓
# 识别结果
# 读取原图和边缘检测后的图像
image_1 = cv2.imread('hanzi1.jpg')
image_6 = cv2.imread('image_6.jpg', cv2.IMREAD_GRAYSCALE)
# 寻找轮廓
contours, _ = cv2.findContours(image_6, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 在原图上画出轮廓
for contour in contours:
    x, y, w, h = cv2.boundingRect(contour)
    cv2.rectangle(image_1, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 保存结果
cv2.imwrite('image_7.jpg', image_1)

## 8. 展示结果
from PIL import Image

def open_image(file_path):
    try:
        return Image.open(file_path)
    except IOError as e:
        print(f"无法打开图像文件 {file_path}: {e}")
        return None

images = ['hanzi1.jpg', 'image_1.jpg', 'image_2.jpg', 'image_3.jpg', 'image_4.jpg', 'image_5.jpg', 'image_6.jpg', 'image_7.jpg']
imgs = []

for img_path in images:
    img = open_image(img_path)
    if img is not None:
        imgs.append(img)
    else:
        print(f"跳过无法打开的图像 {img_path}")

if imgs:
    total_width = sum(img.width for img in imgs)
    max_height = max(img.height for img in imgs)
    result_img = Image.new('RGB', (total_width, max_height))   

    x_offset = 0
    for img in imgs:
        result_img.paste(img, (x_offset, 0))
        x_offset += img.width

    result_img.show()
    result_img.save('最终.jpg')
else:
    print("没有图像可以处理。")






from PIL import Image
import os

# 定义一个函数来处理图像并保存
def process_and_save_image(image_path, output_path):
    try:
        # 打开图像文件
        img = Image.open(image_path)
        # 这里可以添加任何图像处理步骤
        # 例如：img = some_image_processing_function(img)

        # 显示图像
        img.show()

        # 保存图像
        img.save(output_path)
        print(f"图像已保存为：{output_path}")
    except IOError as e:
        print(f"无法处理或保存图像 {image_path}: {e}")

# 图像文件列表
image_files = ['hanzi1.jpg', 'image_1.jpg', 'image_2.jpg', 'image_3.jpg', 'image_4.jpg', 'image_5.jpg', 'image_6.jpg', 'image_7.jpg']
output_files = ['original.jpg', 'gray.jpg', 'binary.jpg', 'eroded.jpg', 'dilated.jpg', 'closed.jpg', 'canny.jpg', 'contours.jpg']

# 确保输出目录存在
output_dir = 'processed_images'
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# 处理和保存每个图像
for image_file, output_file in zip(image_files, output_files):
    output_path = os.path.join(output_dir, output_file)
    process_and_save_image(image_file, output_path)


